package com.kelai.resource.impl;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.kelai.common.BiFactory;
import com.kelai.domain.*;
import com.kelai.dto.DeviceExcelDto;
import com.kelai.dto.ShopExcelDto;
import com.kelai.dto.SonyDeviceExcelDto;
import com.kelai.dto.SonyShopExcelDto;
import com.kelai.resource.IDeviceDataResource;
import com.kelai.resource.JsonCommonResource;
import com.kelai.response.JsonResponse;
import com.kelai.response.Response;
import com.kelai.service.ICommonService;
import com.kelai.service.ICustomerService;
import com.kelai.service.IDeviceDataService;
import com.kelai.service.IStaticService;
import com.kelai.service.impl.DefaultCommonService;
import com.kelai.utils.BreezeeUtils;
import com.kelai.utils.ExcelUtils;
import javafx.util.Callback;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalField;
import java.time.temporal.WeekFields;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备数据资源
 * Created by Silence on 2016/11/26.
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/data")
public class DefaultDeviceDataResource extends JsonCommonResource implements IDeviceDataResource {
    private final static Logger logger = LoggerFactory.getLogger(DefaultDeviceDataResource.class);
    @Resource
    private IDeviceDataService deviceDataService;
    @Resource
    private ICustomerService customerService;
    @Resource
    private IStaticService staticService;

    private ICommonService deviceService;
    private ICommonService shopDataHourService;
    private ICommonService shopDataDayService;
    private ICommonService shopDataWeekService;
    private ICommonService shopDataMonthService;
    private ICommonService deviceDataHourService;
    private ICommonService deviceDataDayService;
    private ICommonService deviceDataWeekService;
    private ICommonService deviceDataMonthService;


    //实时
    private static final String LIDU_REAL_TIME = "0";
    //小时
    private static final String LIDU_HOUR = "2";
    //天
    private static final String LIDU_DAY = "3";
    //周
    private static final String LIDU_WEEK = "4";
    //月
    private static final String LIDU_MONTH = "5";


    @Override
    public Response<DeviceDataEntity> page(@RequestBody DeviceDataEntity deviceDataEntity) {
//        Sort sort = new Sort(Sort.Direction.DESC, "happenTime", "id");
        Sort sort = new Sort(Sort.Direction.DESC, "customerId","happenTime");
        deviceDataEntity.getProperties().put("_sort", sort);
        return _pageAll(deviceDataService, deviceDataEntity);
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @Override
    public Response<AbstractEntity> dataQuery(@RequestBody DeviceDataEntity deviceDataEntity) {
        Object _lidu = deviceDataEntity.getProperties().get("_lidu");
        JsonResponse rep = JsonResponse.OK();
        Object startDate = deviceDataEntity.getProperties().get("_startDate");
        Object endDate = deviceDataEntity.getProperties().get("_endDate");
        String lidu = _lidu == null ? "0" : _lidu.toString();
        Object _sumType = deviceDataEntity.getProperties().get("_radio");
        String sumType = _sumType == null ? "shop" : _sumType.toString();
        Sort sort = new Sort(Sort.Direction.DESC, "customerId","happenTime");
        deviceDataEntity.getProperties().put("_sort", sort);
        switch (lidu){//粒度
            case LIDU_HOUR :
                if (sumType.equals("shop")) {
                    ShopDataHourEntity sdhe = new ShopDataHourEntity();
                    sdhe.getProperties().putAll(deviceDataEntity.getProperties());
                    sdhe.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    sdhe.getProperties().remove("device_id_obj_ae");
                    checkDate(sdhe, startDate, endDate);
                    rep = _pageAllByBi("SHOP_HOUR", sdhe.getProperties());
                    EmptyEntity sumEntity = staticService.sumForShopHour(sdhe.getProperties());
                    rep.setExtProps(sumEntity.getProperties());

                } else if (sumType.equals("device")) {
                    DeviceDataHourEntity ddhe = new DeviceDataHourEntity();
                    ddhe.getProperties().putAll(deviceDataEntity.getProperties());
                    ddhe.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddhe, startDate, endDate);

                    List<String> shopIds = (List<String>)deviceDataEntity.getProperties().get("_shopIds");
                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopType = deviceDataEntity.getProperties().get("shopType");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");

                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId)) && (deviceId == null || Objects.equals("",deviceId)) && (shopIds == null || Objects.equals("",shopIds))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddhe.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddhe.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddhe.getProperties().put("_deviceIds",deviceList);
                    }

                    rep = _pageAllByBi("DEVICE_HOUR", ddhe.getProperties());
                    EmptyEntity sumEntity = staticService.sumForDeviceHour(ddhe.getProperties());
                    rep.setExtProps(sumEntity.getProperties());
                }
                break;
            case LIDU_DAY :
                if (sumType.equals("shop")) {
                    ShopDataDayEntity sdde = new ShopDataDayEntity();
                    sdde.getProperties().putAll(deviceDataEntity.getProperties());
                    sdde.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    sdde.getProperties().remove("device_id_obj_ae");
                    checkDate(sdde, startDate, endDate);
                    rep = _pageAllByBi("SHOP_DAY", sdde.getProperties());
                    EmptyEntity sumEntity = staticService.sumForShopDay(sdde.getProperties());
                    rep.setExtProps(sumEntity.getProperties());
                } else if (sumType.equals("device")) {
                    DeviceDataDayEntity ddde = new DeviceDataDayEntity();
                    ddde.getProperties().putAll(deviceDataEntity.getProperties());
                    ddde.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddde, startDate, endDate);

                    List<String> shopIds = (List<String>)deviceDataEntity.getProperties().get("_shopIds");
                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopType = deviceDataEntity.getProperties().get("shopType");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");


                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId)) && (deviceId == null || Objects.equals("",deviceId))&& (shopIds == null || Objects.equals("",shopIds))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddde.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddde.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddde.getProperties().put("_deviceIds",deviceList);
                    }
                    rep = _pageAllByBi("DEVICE_DAY", ddde.getProperties());
                    EmptyEntity sumEntity = staticService.sumForDeviceDay(ddde.getProperties());
                    rep.setExtProps(sumEntity.getProperties());
                }
                break;
            case LIDU_WEEK :
                if (sumType.equals("shop")) {
                    ShopDataWeekEntity sdwe = new ShopDataWeekEntity();
                    sdwe.getProperties().putAll(deviceDataEntity.getProperties());
                    sdwe.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    sdwe.getProperties().remove("device_id_obj_ae");
                    checkDate(sdwe, startDate, endDate);
                    rep = _pageAllByBi("SHOP_WEEK", sdwe.getProperties());
                    EmptyEntity sumEntity = staticService.sumForShopWeek(sdwe.getProperties());
                    rep.setExtProps(sumEntity.getProperties());

                } else if (sumType.equals("device")) {
                    DeviceDataWeekEntity ddwe = new DeviceDataWeekEntity();
                    ddwe.getProperties().putAll(deviceDataEntity.getProperties());
                    ddwe.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddwe, startDate, endDate);

                    List<String> shopIds = (List<String>)deviceDataEntity.getProperties().get("_shopIds");
                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopType = deviceDataEntity.getProperties().get("shopType");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");
                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId)) && (shopIds == null || Objects.equals("",shopIds)) && (deviceId == null || Objects.equals("",deviceId))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddwe.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddwe.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddwe.getProperties().put("_deviceIds",deviceList);
                    }

                    rep = _pageAllByBi("DEVICE_WEEK", ddwe.getProperties());
                    EmptyEntity sumEntity = staticService.sumForDeviceWeek(ddwe.getProperties());
                    rep.setExtProps(sumEntity.getProperties());
                }
                break;
            case LIDU_MONTH :
                if (sumType.equals("shop")) {
                    ShopDataMonthEntity sdme = new ShopDataMonthEntity();
                    sdme.getProperties().putAll(deviceDataEntity.getProperties());
                    sdme.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    sdme.getProperties().remove("device_id_obj_ae");
                    checkDate(sdme, startDate, endDate);
                    rep = _pageAllByBi("SHOP_MONTH", sdme.getProperties());
                    EmptyEntity sumEntity = staticService.sumForShopMonth(sdme.getProperties());
                    rep.setExtProps(sumEntity.getProperties());

                } else if (sumType.equals("device")) {
                    DeviceDataMonthEntity ddme = new DeviceDataMonthEntity();
                    ddme.getProperties().putAll(deviceDataEntity.getProperties());
                    ddme.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddme, startDate, endDate);

                    List<String> shopIds = (List<String>)deviceDataEntity.getProperties().get("_shopIds");
                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopType = deviceDataEntity.getProperties().get("shopType");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");
                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId)) && (shopIds == null || Objects.equals("",shopIds)) && (deviceId == null || Objects.equals("",deviceId))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddme.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddme.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddme.getProperties().put("_deviceIds",deviceList);
                    }

                    rep = _pageAllByBi("DEVICE_MONTH", ddme.getProperties());
                    EmptyEntity sumEntity = staticService.sumForDeviceMonth(ddme.getProperties());
                    rep.setExtProps(sumEntity.getProperties());
                }
                break;
            default: //TODO 实时查询
//                Sort sort = new Sort(Sort.Direction.DESC, "happenTime", "id");
//                deviceDataEntity.getProperties().put("_sort", sort);
                if (startDate != null && StringUtils.isNotEmpty(String.valueOf(startDate))) {
                    deviceDataEntity.getProperties().put("happenTime_gt", Long.parseLong(startDate.toString().replaceAll("-", "") + "000000"));

                }else{
                    deviceDataEntity.getProperties().remove("happenTime_gt");
                }
                if (endDate != null && StringUtils.isNotEmpty(String.valueOf(endDate))) {
                    deviceDataEntity.getProperties().put("happenTime_le", Long.parseLong(endDate.toString().replaceAll("-", "") + "235959"));
                }else{
                    deviceDataEntity.getProperties().remove("happenTime_le");
                }
                rep = _pageAll(deviceDataService, deviceDataEntity);
//                EmptyEntity sumEntity = staticService.sumForRealTime(deviceDataEntity.getProperties());
//                rep.setExtProps(sumEntity.getProperties());
                break;
        }

        Map<String,Object> extProps = new HashMap<String,Object>();
        Integer inCnt = 0;//进店总数
        Integer outCnt = 0;//出店总数
        if(rep.getRows()!=null&&rep.getRows().size()>0){
            for (Object obj:rep.getRows()) {
                if(obj != null && ((DXInOut)obj) != null){
                    inCnt +=   ((DXInOut)obj).getDxin() == null ? 0 : ((DXInOut)obj).getDxin();
                    outCnt += ((DXInOut)obj).getDxout() == null ? 0 : ((DXInOut)obj).getDxout();
                }
            }
        }
        extProps.put("inCnt",inCnt);
        extProps.put("outCnt",outCnt);
        rep.setExtProps(extProps);
        return rep;
    }

    /**
     * 对比分析
     * @param deviceDataEntity 查询条件
     * @return
     */
    @RequestMapping(value = "/compare", method = RequestMethod.POST)
    @Override
    public Response<AbstractEntity> compare(@RequestBody DeviceDataEntity deviceDataEntity) {
        Object _lidu = deviceDataEntity.getProperties().get("_lidu");
        JsonResponse rep = JsonResponse.OK();
        Object startDate = deviceDataEntity.getProperties().get("_startDate");
        Object endDate = deviceDataEntity.getProperties().get("_endDate");
        String lidu = _lidu == null ? "0" : _lidu.toString();
        Object _sumType = deviceDataEntity.getProperties().get("_radio");
        String sumType = _sumType == null ? "shop" : _sumType.toString();
        switch (lidu){//粒度
            case LIDU_HOUR :
                if (sumType.equals("shop")) {
                    ShopDataHourEntity she = new ShopDataHourEntity();
                    she.getProperties().putAll(deviceDataEntity.getProperties());
                    she.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    she.getProperties().remove("device_id_obj_ae");
                    checkDate(she, startDate, endDate);
                    rep = _pageAllByBi("SHOP_HOUR", she.getProperties());

                } else if (sumType.equals("device")) {
                    DeviceDataHourEntity ddhe = new DeviceDataHourEntity();
                    ddhe.getProperties().putAll(deviceDataEntity.getProperties());
                    ddhe.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddhe, startDate, endDate);

                    List<String> shopIds = (List<String>)deviceDataEntity.getProperties().get("_shopIds");
                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopType = deviceDataEntity.getProperties().get("shopType");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");

                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId))&& (shopIds == null || Objects.equals("",shopIds)) && (deviceId == null || Objects.equals("",deviceId))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddhe.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddhe.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddhe.getProperties().put("_deviceIds",deviceList);
                    }

                    rep = _pageAllByBi("DEVICE_HOUR", ddhe.getProperties());
                }
                break;
            case LIDU_DAY :
                if (sumType.equals("shop")) {
                    ShopDataDayEntity she = new ShopDataDayEntity();
                    she.getProperties().putAll(deviceDataEntity.getProperties());
                    she.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    she.getProperties().remove("device_id_obj_ae");
                    checkDate(she, startDate, endDate);
                    rep = _pageAllByBi("SHOP_DAY", she.getProperties());
                } else if (sumType.equals("device")) {
                    DeviceDataDayEntity ddde = new DeviceDataDayEntity();
                    ddde.getProperties().putAll(deviceDataEntity.getProperties());
                    ddde.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddde, startDate, endDate);

                    List<String> shopIds = (List<String>)deviceDataEntity.getProperties().get("_shopIds");
                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopType = deviceDataEntity.getProperties().get("shopType");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");
                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId))&& (shopIds == null || Objects.equals("",shopIds)) && (deviceId == null || Objects.equals("",deviceId))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddde.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddde.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddde.getProperties().put("_deviceIds",deviceList);
                    }

                    rep = _pageAllByBi("DEVICE_DAY", ddde.getProperties());
                }
                break;
            case LIDU_WEEK :
                if (sumType.equals("shop")) {
                    ShopDataWeekEntity sdwe = new ShopDataWeekEntity();
                    sdwe.getProperties().putAll(deviceDataEntity.getProperties());
                    sdwe.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    sdwe.getProperties().remove("device_id_obj_ae");
                    checkDate(sdwe, startDate, endDate);
                    rep = _pageAllByBi("SHOP_WEEK", sdwe.getProperties());

                } else if (sumType.equals("device")) {
                    DeviceDataWeekEntity ddwe = new DeviceDataWeekEntity();
                    ddwe.getProperties().putAll(deviceDataEntity.getProperties());
                    ddwe.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddwe, startDate, endDate);

                    List<String> shopIds = (List<String>)deviceDataEntity.getProperties().get("_shopIds");
                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopType = deviceDataEntity.getProperties().get("shopType");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");
                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId))&& (shopIds == null || Objects.equals("",shopIds)) && (deviceId == null || Objects.equals("",deviceId))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddwe.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddwe.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddwe.getProperties().put("_deviceIds",deviceList);
                    }

                    rep = _pageAllByBi("DEVICE_WEEK", ddwe.getProperties());
                }
                break;
            case LIDU_MONTH :
                if (sumType.equals("shop")) {
                    ShopDataMonthEntity sdme = new ShopDataMonthEntity();
                    sdme.getProperties().putAll(deviceDataEntity.getProperties());
                    sdme.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    sdme.getProperties().remove("device_id_obj_ae");
                    checkDate(sdme, startDate, endDate);
                    rep = _pageAllByBi("SHOP_MONTH", sdme.getProperties());

                } else if (sumType.equals("device")) {
                    DeviceDataMonthEntity ddme = new DeviceDataMonthEntity();
                    ddme.getProperties().putAll(deviceDataEntity.getProperties());
                    ddme.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddme, startDate, endDate);

                    List<String> shopIds = (List<String>)deviceDataEntity.getProperties().get("_shopIds");
                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopType = deviceDataEntity.getProperties().get("shopType");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");
                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId)) && (shopIds == null || Objects.equals("",shopIds))&& (deviceId == null || Objects.equals("",deviceId))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddme.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddme.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddme.getProperties().put("_deviceIds",deviceList);
                    }

                    rep = _pageAllByBi("DEVICE_MONTH", ddme.getProperties());
                }
                break;
            default:
//                Sort sort = new Sort(Sort.Direction.DESC, "happenTime", "id");
//                deviceDataEntity.getProperties().put("_sort", sort);
                Sort sort = new Sort(Sort.Direction.DESC, "customerId","happenTime");
                deviceDataEntity.getProperties().put("_sort", sort);
                if (startDate != null) {
                    deviceDataEntity.getProperties().put("happenTime_gt", Long.parseLong(startDate.toString().replaceAll("-", "") + "000000"));
                }
                if (endDate != null) {
                    deviceDataEntity.getProperties().put("happenTime_le", Long.parseLong(endDate.toString().replaceAll("-", "") + "000000"));
                }
                rep = _pageAll(deviceDataService, deviceDataEntity);
                break;
        }

        Map<String,Object> extProps = new HashMap<String,Object>();
        Integer inCnt = 0;//进店总数
        Integer outCnt = 0;//出店总数
        if(rep.getRows()!=null&&rep.getRows().size()>0){
            for (Object obj:rep.getRows()) {
                inCnt+=((DXInOut)obj).getDxin();
                outCnt+=((DXInOut)obj).getDxout();
            }
        }
        extProps.put("inCnt",inCnt);
        extProps.put("outCnt",outCnt);
        rep.setExtProps(extProps);
        return rep;
    }

    /**
     * 时间对比
     * @param deviceDataEntity 查询条件
     * @return
     */
    @RequestMapping(value = "/dateCompare", method = RequestMethod.POST)
    @Override
    public Response<EmptyEntity> dateCompare(@RequestBody DeviceDataEntity deviceDataEntity) throws ParseException {

        JsonResponse rep = JsonResponse.OK();

        deviceDataEntity.getProperties().put("_startDate", deviceDataEntity.getProperties().get("_startDate1"));
        deviceDataEntity.getProperties().put("_endDate", deviceDataEntity.getProperties().get("_endDate1"));
        JsonResponse<ShopDataDayEntity> rep1 = _pageAllByBi("SHOP_DAY", deviceDataEntity.getProperties());
        List<ShopDataDayEntity> list1 = (List<ShopDataDayEntity>)rep1.getRows();

        deviceDataEntity.getProperties().put("_startDate", deviceDataEntity.getProperties().get("_startDate2"));
        deviceDataEntity.getProperties().put("_endDate", deviceDataEntity.getProperties().get("_endDate2"));
        JsonResponse<ShopDataDayEntity> rep2 = _pageAllByBi("SHOP_DAY", deviceDataEntity.getProperties());
        List<ShopDataDayEntity> list2 = (List<ShopDataDayEntity>)rep2.getRows();

        List<EmptyEntity> l = new ArrayList<>();
        if(list1 != null && list2 != null && list1.size() == list2.size()){
            for(int i = 0 ; i < list1.size() ; i++){
                EmptyEntity emptyEntity = new EmptyEntity();
                emptyEntity.getProperties().put("day1",list1.get(i).getHappenTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString());
                emptyEntity.getProperties().put("day2",list2.get(i).getHappenTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString());
                emptyEntity.getProperties().put("num1",list1.get(i).getDxin());
                emptyEntity.getProperties().put("num2",list2.get(i).getDxin());
                emptyEntity.getProperties().put("index","第"+(i+1)+"天");
                l.add(emptyEntity);
            }
        }

        return JsonResponse.build(l);

    }

    /**
     * 导出
     * @param
     * @return
     */
    @RequestMapping(value = "/export_download", method = RequestMethod.POST , produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<InputStreamResource> export(String customerId , String _customerId,
                                                      String _startDate , String _endDate,
                                                      String _lidu , String _radio,
                                                      String shopType , String customer_id_obj_ae,
                                                      String device_id_obj_ae,
                                                      String _loginTopCustomer,
                                                      String _shopIdsStr) throws IOException {

        List<String> shopIds = null;
        if(_shopIdsStr!=null&&!"".equals(_shopIdsStr.trim())){
            shopIds = new ArrayList<String>();
            for (String shopId:_shopIdsStr.split("\\|")) {
                shopIds.add(shopId);
            }
        }

        DeviceDataEntity deviceDataEntity = new DeviceDataEntity();
        deviceDataEntity.getProperties().put("_customerId",_customerId);
        deviceDataEntity.getProperties().put("customerId",customerId);
        deviceDataEntity.getProperties().put("shopType",shopType);
        deviceDataEntity.getProperties().put("_endDate",_endDate);
        deviceDataEntity.getProperties().put("_lidu",_lidu);
        deviceDataEntity.getProperties().put("_radio",_radio);
        deviceDataEntity.getProperties().put("_startDate",_startDate);
        deviceDataEntity.getProperties().put("customer_id_obj_ae",customer_id_obj_ae);
        deviceDataEntity.getProperties().put("device_id_obj_ae",device_id_obj_ae);
        deviceDataEntity.getProperties().put("_shopIds",shopIds);


        String startDate = _startDate;
        String endDate = _endDate;
        String lidu = _lidu == null ? "0" : _lidu.toString();
        Object _sumType = _radio;
        String sumType = _sumType == null ? "device" : _sumType.toString();

        File templateFile = null;

        switch (lidu){//粒度
            case LIDU_HOUR :
                if (sumType.equals("shop")) {
                    ShopDataHourEntity she = new ShopDataHourEntity();
                    she.getProperties().putAll(deviceDataEntity.getProperties());
                    she.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    she.getProperties().remove("device_id_obj_ae");
                    checkDate(she, startDate, endDate);
                    List<ShopDataHourEntity> list = new BiFactory()
                            .createService("SHOP_HOUR").listAll(she.getProperties());

                    if("索尼中国".equals(_loginTopCustomer)){
                        List<SonyShopExcelDto> datas = Lists.newArrayList();

                        for(ShopDataHourEntity item : list){
                            SonyShopExcelDto dto = new SonyShopExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));


                            String dateStr = BreezeeUtils.dateToStr(item.getHappenTime());
                            String dayStr = dateStr.substring(0,10);
                            String startHourStr = dateStr.substring(11,13);
                            Integer endHour = Integer.valueOf(startHourStr)+1;
                            dto.setHappenTime(dayStr+" "+startHourStr+":00-"+endHour+":00");

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(SonyShopExcelDto.class, "店铺小时统计", "店铺小时统计", datas);
                    }else{
                        List<ShopExcelDto> datas = Lists.newArrayList();

                        for(ShopDataHourEntity item : list){
                            ShopExcelDto dto = new ShopExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));
                            dto.setDxout(String.valueOf(item.getDxout()));

                            String dateStr = BreezeeUtils.dateToStr(item.getHappenTime());
                            String dayStr = dateStr.substring(0,10);
                            String startHourStr = dateStr.substring(11,13);
                            Integer endHour = Integer.valueOf(startHourStr)+1;
                            dto.setHappenTime(dayStr+" "+startHourStr+":00-"+endHour+":00");

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(ShopExcelDto.class, "店铺小时统计", "店铺小时统计", datas);
                    }



                } else if (sumType.equals("device")) {
                    DeviceDataHourEntity ddhe = new DeviceDataHourEntity();
                    ddhe.getProperties().putAll(deviceDataEntity.getProperties());
                    ddhe.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddhe, startDate, endDate);

                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");
                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId))&& (shopIds == null || Objects.equals("",shopIds)) && (deviceId == null || Objects.equals("",deviceId))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddhe.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddhe.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddhe.getProperties().put("_deviceIds",deviceList);
                    }

                    List<DeviceDataHourEntity> list = new BiFactory()
                            .createService("DEVICE_HOUR").listAll(ddhe.getProperties());

                    if("索尼中国".equals(_loginTopCustomer)){
                        List<SonyDeviceExcelDto> datas = Lists.newArrayList();

                        for(DeviceDataHourEntity item : list){
                            SonyDeviceExcelDto dto = new SonyDeviceExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));

                            String dateStr = BreezeeUtils.dateToStr(item.getHappenTime());
                            String dayStr = dateStr.substring(0,10);
                            String startHourStr = dateStr.substring(11,13);
                            Integer endHour = Integer.valueOf(startHourStr)+1;
                            dto.setHappenTime(dayStr+" "+startHourStr+":00-"+endHour+":00");

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            dto.setDeviceName(item.getName());
                            dto.setDevicePosition(item.getPosition());

                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(SonyDeviceExcelDto.class, "设备小时统计", "设备小时统计", datas);
                    }else{
                        List<DeviceExcelDto> datas = Lists.newArrayList();

                        for(DeviceDataHourEntity item : list){
                            DeviceExcelDto dto = new DeviceExcelDto();
                            dto.setDxout(String.valueOf(item.getDxout()));
                            dto.setDxin(String.valueOf(item.getDxin()));

                            String dateStr = BreezeeUtils.dateToStr(item.getHappenTime());
                            String dayStr = dateStr.substring(0,10);
                            String startHourStr = dateStr.substring(11,13);
                            Integer endHour = Integer.valueOf(startHourStr)+1;
                            dto.setHappenTime(dayStr+" "+startHourStr+":00-"+endHour+":00");

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            dto.setDeviceName(item.getName());
                            dto.setDevicePosition(item.getPosition());

                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(DeviceExcelDto.class, "设备小时统计", "设备小时统计", datas);
                    }


                }
                break;
            case LIDU_DAY :
                if (sumType.equals("shop")) {
                    ShopDataDayEntity she = new ShopDataDayEntity();
                    she.getProperties().putAll(deviceDataEntity.getProperties());
                    she.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    she.getProperties().remove("device_id_obj_ae");
                    checkDate(she, startDate, endDate);
                    List<ShopDataDayEntity> list = new BiFactory()
                            .createService("SHOP_DAY").listAll(she.getProperties());

                    if("索尼中国".equals(_loginTopCustomer)){
                        List<SonyShopExcelDto> datas = Lists.newArrayList();

                        for(ShopDataDayEntity item : list){
                            SonyShopExcelDto dto = new SonyShopExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));

                            String dayStr = BreezeeUtils.dateToStr(item.getHappenTime()).substring(0,10);
                            dto.setHappenTime(dayStr);

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(SonyShopExcelDto.class, "店铺日统计", "店铺日统计", datas);
                    }else{
                        List<ShopExcelDto> datas = Lists.newArrayList();

                        for(ShopDataDayEntity item : list){
                            ShopExcelDto dto = new ShopExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));
                            dto.setDxout(String.valueOf(item.getDxout()));

                            String dayStr = BreezeeUtils.dateToStr(item.getHappenTime()).substring(0,10);
                            dto.setHappenTime(dayStr);

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(ShopExcelDto.class, "店铺日统计", "店铺日统计", datas);
                    }


                } else if (sumType.equals("device")) {
                    DeviceDataDayEntity ddde = new DeviceDataDayEntity();
                    ddde.getProperties().putAll(deviceDataEntity.getProperties());
                    ddde.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddde, startDate, endDate);

                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");
                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId))&& (shopIds == null || Objects.equals("",shopIds)) && (deviceId == null || Objects.equals("",deviceId))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddde.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddde.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddde.getProperties().put("_deviceIds",deviceList);
                    }

                    List<DeviceDataDayEntity> list = new BiFactory()
                            .createService("DEVICE_DAY").listAll(ddde.getProperties());

                    if("索尼中国".equals(_loginTopCustomer)){
                        List<SonyDeviceExcelDto> datas = Lists.newArrayList();

                        for(DeviceDataDayEntity item : list){
                            SonyDeviceExcelDto dto = new SonyDeviceExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));

                            String dayStr = BreezeeUtils.dateToStr(item.getHappenTime()).substring(0,10);
                            dto.setHappenTime(dayStr);

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            dto.setDeviceName(item.getName());
                            dto.setDevicePosition(item.getPosition());

                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(SonyDeviceExcelDto.class, "设备日统计", "设备日统计", datas);
                    }else{
                        List<DeviceExcelDto> datas = Lists.newArrayList();

                        for(DeviceDataDayEntity item : list){
                            DeviceExcelDto dto = new DeviceExcelDto();
                            dto.setDxout(String.valueOf(item.getDxout()));
                            dto.setDxin(String.valueOf(item.getDxin()));

                            String dayStr = BreezeeUtils.dateToStr(item.getHappenTime()).substring(0,10);
                            dto.setHappenTime(dayStr);

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            dto.setDeviceName(item.getName());
                            dto.setDevicePosition(item.getPosition());

                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(DeviceExcelDto.class, "设备日统计", "设备日统计", datas);
                    }


                }
                break;
            case LIDU_WEEK :
                if (sumType.equals("shop")) {
                    ShopDataWeekEntity sdwe = new ShopDataWeekEntity();
                    sdwe.getProperties().putAll(deviceDataEntity.getProperties());
                    sdwe.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    sdwe.getProperties().remove("device_id_obj_ae");
                    checkDate(sdwe, startDate, endDate);
                    List<ShopDataWeekEntity> list = new BiFactory()
                            .createService("SHOP_WEEK").listAll(sdwe.getProperties());

                    if("索尼中国".equals(_loginTopCustomer)){
                        List<SonyShopExcelDto> datas = Lists.newArrayList();

                        for(ShopDataWeekEntity item : list){
                            SonyShopExcelDto dto = new SonyShopExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));

                            TemporalField fieldISO = WeekFields.of(Locale.ENGLISH).dayOfWeek();
                            LocalDateTime firstDay = LocalDateTime.of(Integer.valueOf(_startDate.substring(0,4)),1,1,0,0);
                            LocalDateTime startDay = firstDay.plusWeeks(Integer.valueOf(item.getHappenTime())-1).with(fieldISO,1);
                            LocalDateTime endDay = firstDay.plusWeeks(Integer.valueOf(item.getHappenTime())-1).with(fieldISO,7);
                            dto.setHappenTime(startDay.toString().substring(0,10)+"~"+endDay.toString().substring(0,10)+" 第"+item.getHappenTime()+"周");
                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(SonyShopExcelDto.class, "店铺周统计", "店铺周统计", datas);
                    }else{
                        List<ShopExcelDto> datas = Lists.newArrayList();

                        for(ShopDataWeekEntity item : list){
                            ShopExcelDto dto = new ShopExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));
                            dto.setDxout(String.valueOf(item.getDxout()));

                            TemporalField fieldISO = WeekFields.of(Locale.ENGLISH).dayOfWeek();
                            LocalDateTime firstDay = LocalDateTime.of(Integer.valueOf(_startDate.substring(0,4)),1,1,0,0);
                            LocalDateTime startDay = firstDay.plusWeeks(Integer.valueOf(item.getHappenTime())-1).with(fieldISO,1);
                            LocalDateTime endDay = firstDay.plusWeeks(Integer.valueOf(item.getHappenTime())-1).with(fieldISO,7);
                            dto.setHappenTime(startDay.toString().substring(0,10)+"~"+endDay.toString().substring(0,10)+" 第"+item.getHappenTime()+"周");
                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(ShopExcelDto.class, "店铺周统计", "店铺周统计", datas);
                    }



                } else if (sumType.equals("device")) {
                    DeviceDataWeekEntity ddwe = new DeviceDataWeekEntity();
                    ddwe.getProperties().putAll(deviceDataEntity.getProperties());
                    ddwe.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddwe, startDate, endDate);

                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");
                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId))&& (shopIds == null || Objects.equals("",shopIds)) && (deviceId == null || Objects.equals("",deviceId))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddwe.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddwe.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddwe.getProperties().put("_deviceIds",deviceList);
                    }

                    List<DeviceDataWeekEntity> list = new BiFactory()
                            .createService("DEVICE_WEEK").listAll(ddwe.getProperties());

                    if("索尼中国".equals(_loginTopCustomer)){
                        List<SonyDeviceExcelDto> datas = Lists.newArrayList();

                        for(DeviceDataWeekEntity item : list){
                            SonyDeviceExcelDto dto = new SonyDeviceExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));
                            TemporalField fieldISO = WeekFields.of(Locale.ENGLISH).dayOfWeek();
                            LocalDateTime firstDay = LocalDateTime.of(Integer.valueOf(_startDate.substring(0,4)),1,1,0,0);
                            LocalDateTime startDay = firstDay.plusWeeks(Integer.valueOf(item.getHappenTime())-1).with(fieldISO,1);
                            LocalDateTime endDay = firstDay.plusWeeks(Integer.valueOf(item.getHappenTime())-1).with(fieldISO,7);
                            dto.setHappenTime(startDay.toString().substring(0,10)+"~"+endDay.toString().substring(0,10)+" 第"+item.getHappenTime()+"周");
                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            dto.setDeviceName(item.getName());
                            dto.setDevicePosition(item.getPosition());

                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(SonyDeviceExcelDto.class, "设备周统计", "设备周统计", datas);
                    }else{
                        List<DeviceExcelDto> datas = Lists.newArrayList();

                        for(DeviceDataWeekEntity item : list){
                            DeviceExcelDto dto = new DeviceExcelDto();
                            dto.setDxout(String.valueOf(item.getDxout()));
                            dto.setDxin(String.valueOf(item.getDxin()));
                            TemporalField fieldISO = WeekFields.of(Locale.ENGLISH).dayOfWeek();
                            LocalDateTime firstDay = LocalDateTime.of(Integer.valueOf(_startDate.substring(0,4)),1,1,0,0);
                            LocalDateTime startDay = firstDay.plusWeeks(Integer.valueOf(item.getHappenTime())-1).with(fieldISO,1);
                            LocalDateTime endDay = firstDay.plusWeeks(Integer.valueOf(item.getHappenTime())-1).with(fieldISO,7);
                            dto.setHappenTime(startDay.toString().substring(0,10)+"~"+endDay.toString().substring(0,10)+" 第"+item.getHappenTime()+"周");
                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            dto.setDeviceName(item.getName());
                            dto.setDevicePosition(item.getPosition());

                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(DeviceExcelDto.class, "设备周统计", "设备周统计", datas);
                    }


                }
                break;
            case LIDU_MONTH :
                if (sumType.equals("shop")) {
                    ShopDataMonthEntity sdme = new ShopDataMonthEntity();
                    sdme.getProperties().putAll(deviceDataEntity.getProperties());
                    sdme.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    sdme.getProperties().remove("device_id_obj_ae");
                    checkDate(sdme, startDate, endDate);
                    List<ShopDataMonthEntity> list = new BiFactory()
                            .createService("SHOP_MONTH").listAll(sdme.getProperties());

                    if("索尼中国".equals(_loginTopCustomer)){
                        List<SonyShopExcelDto> datas = Lists.newArrayList();

                        for(ShopDataMonthEntity item : list){
                            SonyShopExcelDto dto = new SonyShopExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));

                            String dayStr = BreezeeUtils.dateToStr(item.getHappenTime()).substring(0,7);
                            dto.setHappenTime(dayStr);

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(SonyShopExcelDto.class, "店铺月统计", "店铺月统计", datas);
                    }else{
                        List<ShopExcelDto> datas = Lists.newArrayList();

                        for(ShopDataMonthEntity item : list){
                            ShopExcelDto dto = new ShopExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));
                            dto.setDxout(String.valueOf(item.getDxout()));

                            String dayStr = BreezeeUtils.dateToStr(item.getHappenTime()).substring(0,7);
                            dto.setHappenTime(dayStr);

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(ShopExcelDto.class, "店铺月统计", "店铺月统计", datas);
                    }



                } else if (sumType.equals("device")) {
                    DeviceDataMonthEntity ddme = new DeviceDataMonthEntity();
                    ddme.getProperties().putAll(deviceDataEntity.getProperties());
                    ddme.getProperties().put("year", deviceDataEntity.getProperties().get("_year"));
                    checkDate(ddme, startDate, endDate);

                    Object shopId = deviceDataEntity.getProperties().get("customer_id_obj_ae");
                    Object deviceId = deviceDataEntity.getProperties().get("device_id_obj_ae");
                    Object shopArea = deviceDataEntity.getProperties().get("_customerId");
                    //选到店铺，不选设备
                    if((shopId != null && !Objects.equals("",shopId))&& (shopIds == null || Objects.equals("",shopIds)) && (deviceId == null || Objects.equals("",deviceId))){
                        List<String> deviceList = findDeviceIdByShop(Lists.newArrayList(shopId.toString()));
                        ddme.getProperties().put("_deviceIds",deviceList);
                    }
                    //选到区域或者类型，不选店铺和设备
                    else if(((shopType != null && StringUtils.isNotEmpty(shopType.toString()))
                            || (shopArea != null && StringUtils.isNotEmpty(shopArea.toString())))
                            && (deviceId == null || Objects.equals("",deviceId))
                            && (shopIds == null || Objects.equals("",shopIds))){

                        List<String> shopIdList = findShopIdByAreaOrType(shopArea,shopType);
                        List<String> deviceList = findDeviceIdByShop(shopIdList);
                        ddme.getProperties().put("_deviceIds",deviceList);
                    }else if(shopIds!=null&&shopIds.size()>0){//客流数据 店铺多选

                        List<String> deviceList = findDeviceIdByShop(shopIds);
                        ddme.getProperties().put("_deviceIds",deviceList);
                    }


                    List<DeviceDataMonthEntity> list = new BiFactory()
                            .createService("DEVICE_MONTH").listAll(ddme.getProperties());

                    if("索尼中国".equals(_loginTopCustomer)){
                        List<SonyDeviceExcelDto> datas = Lists.newArrayList();

                        for(DeviceDataMonthEntity item : list){
                            SonyDeviceExcelDto dto = new SonyDeviceExcelDto();
                            dto.setDxin(String.valueOf(item.getDxin()));

                            String dayStr = BreezeeUtils.dateToStr(item.getHappenTime()).substring(0,7);
                            dto.setHappenTime(dayStr);

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            dto.setDeviceName(item.getName());
                            dto.setDevicePosition(item.getPosition());

                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(SonyDeviceExcelDto.class, "设备月统计", "设备月统计", datas);
                    }else{
                        List<DeviceExcelDto> datas = Lists.newArrayList();

                        for(DeviceDataMonthEntity item : list){
                            DeviceExcelDto dto = new DeviceExcelDto();
                            dto.setDxout(String.valueOf(item.getDxout()));
                            dto.setDxin(String.valueOf(item.getDxin()));

                            String dayStr = BreezeeUtils.dateToStr(item.getHappenTime()).substring(0,7);
                            dto.setHappenTime(dayStr);

                            dto.setCustomerName(item.getCustomerName());
                            dto.setShopName(item.getShopName());
                            dto.setDeviceName(item.getName());
                            dto.setDevicePosition(item.getPosition());

                            datas.add(dto);
                        }
                        templateFile = ExcelUtils.export(DeviceExcelDto.class, "设备月统计", "设备月统计", datas);
                    }


                }
                break;
            default:
//                Sort sort = new Sort(Sort.Direction.DESC, "happenTime", "id");
//                deviceDataEntity.getProperties().put("_sort", sort);
                Sort sort = new Sort(Sort.Direction.DESC, "customerId","happenTime");
                deviceDataEntity.getProperties().put("_sort", sort);
                if (startDate != null) {
                    deviceDataEntity.getProperties().put("happenTime_gt", Long.parseLong(startDate.toString().replaceAll("-", "") + "000000"));
                }
                if (endDate != null) {
                    deviceDataEntity.getProperties().put("happenTime_le", Long.parseLong(endDate.toString().replaceAll("-", "") + "000000"));
                }
//                rep = _pageAll(deviceDataService, deviceDataEntity);
                break;
        }

        FileSystemResource file = new FileSystemResource(templateFile);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename="+new String((file.getFilename()).getBytes("gb2312"), "iso-8859-1"));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    private void checkDate(AbstractEntity entity, Object startDate, Object endDate) {
        try {
            if (startDate != null){
                Date date = BreezeeUtils.str2Date(startDate.toString());
                entity.getProperties().put("happenTime_gt", date);
            }
            if (endDate != null){
                Date date = BreezeeUtils.str2Date(endDate.toString());
                entity.getProperties().put("happenTime_le", date);
            }
        } catch (Exception e) {
            logger.info("~~~~~~~~checkDate error~~~~~~~~~~~~~~~");
            logger.info("startDate : "+startDate+" | endDate : "+endDate);
        }
    }

    @Override
    public Response<DeviceDataEntity> findById(String id) {
        return _findOne(deviceDataService, id, 0);
    }

    @Override
    public Response<DeviceDataEntity> findByCode(String code) {
        return _findOne(deviceDataService, code, 1);
    }

    @Override
    public Response<DeviceDataEntity> save(DeviceDataEntity deviceDataEntity) {
        return _saveInfo(deviceDataService, deviceDataEntity, (Callback<DeviceDataEntity, Object>) param -> {
            param.setCode(param.getId());
            param.setName(param.getSn());
            return null;
        });
    }

    @Override
    public Response<DeviceDataEntity> delete(String id) {
        return _delete(deviceDataService, id);
    }


    //根据区域和类型查找店铺
    private List<String> findShopIdByAreaOrType(Object areaId,Object typeId){
        List<Object[]> shopList = Lists.newArrayList();
        shopList = customerService.findShopsByCusId(areaId+"");

        List<String> shopIdList = Lists.newArrayList();
        if(typeId == null || Objects.equals("",typeId)){
            shopIdList = shopList.stream().map( obj -> {
                return obj[0].toString();
            }).collect(Collectors.toList());
        }else{
            for(Object[] obj : shopList){
                if(Objects.equals(typeId,obj[3] == null ? "" : obj[3].toString())){
                    shopIdList.add(obj[0].toString());
                }
            }
        }
        return shopIdList;
    }

    //根据店铺查找设备
    private List<String> findDeviceIdByShop(List<String> shopIdList){
        DeviceEntity deviceEntity = new DeviceEntity();
        deviceEntity.getProperties().put("customer_id_obj_in_ae", Joiner.on(",").join(shopIdList));
        List<AbstractEntity> list = deviceService.listAll(deviceEntity);
        List<String> deviceList = list.stream().map( device -> device.getId())
                .collect(Collectors.toList());
        return deviceList;
    }


    @RequestMapping(value = "/history", method = RequestMethod.POST)
    public Response<DeviceStateDataEntity> viewHistory(@RequestBody DeviceStateDataEntity condition) {
        Sort sort = new Sort(Sort.Direction.DESC, "happenTime");
        condition.getProperties().put("_sort", sort);
        condition.getProperties().put("happenTime_gt", LocalDate.now().plusDays(-3)
                .format(DateTimeFormatter.BASIC_ISO_DATE)+"000000");
        return _pageAll(deviceDataService, condition);
    }

    @Override
    public void initService() {
        if (deviceService == null)
            deviceService = new DefaultCommonService("deviceRepository");

        if (shopDataHourService == null)
            shopDataHourService = new DefaultCommonService("shopDataHourRepoistory");

        if (shopDataDayService == null)
            shopDataDayService = new DefaultCommonService("shopDataDayRepository");

        if (shopDataWeekService == null)
            shopDataWeekService = new DefaultCommonService("shopDataWeekRepository");

        if (shopDataMonthService == null)
            shopDataMonthService = new DefaultCommonService("shopDataMonthRepository");

        if (deviceDataDayService == null)
            deviceDataDayService = new DefaultCommonService("deviceDataDayRepository");

        if (deviceDataHourService == null)
            deviceDataHourService = new DefaultCommonService("deviceDataHourRepository");

        if (deviceDataWeekService == null)
            deviceDataWeekService = new DefaultCommonService("deviceDataWeekRepository");

        if (deviceDataMonthService == null)
            deviceDataMonthService = new DefaultCommonService("deviceDataMonthRepository");
    }

}
